package servlet;

import pojo.User;
import service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
//登录Servlet
@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    private UserService service = new UserService();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //接受 rememberMe
        String rememberMe = request.getParameter("rememberMe");
        User user = service.login(username, password);
        if(user != null){
            //完成前端记住我功能
            if("1".equals(rememberMe)){
                //向前端发送Cookie记住用户名和密码的信息
                Cookie cookieUsername = new Cookie("username",username);
                Cookie cookiePassword = new Cookie("password",password);
                cookieUsername.setMaxAge( 7*24*3600);
                cookiePassword.setMaxAge( 7*24*3600);
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);
            }else{
//                清除Cookie记住用户名和密码的信息
                Cookie cookieUsername = new Cookie("username",null);
                Cookie cookiePassword = new Cookie("password",null);
                cookieUsername.setMaxAge( 0);
                cookiePassword.setMaxAge( 0);
                response.addCookie(cookieUsername);
                response.addCookie(cookiePassword);
            }
            //登录成功:1.存session  2.重定向到首页
            HttpSession session = request.getSession();
            session.setAttribute("LOGIN_USER",user);
            response.sendRedirect("/selectAll");
        }else {
            // 登录失败:1.存错误信息  2.转发到login.jsp
            String msg="用户名或密码错误";
            request.setAttribute("LOGIN_MSG",msg);
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
}
